package cn.fuxi2022.commons.redis.service.impl;

import cn.fuxi2022.commons.redis.service.CaptchaService;
import cn.fuxi2022.core.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean checkPhoneCount(String phone) {
        // 根据reids获取数据
        // 优雅判空
        // `ofNullable`来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题
        // `orElseGet`：获取数据并且设置数据为空时的默认值
        int count = (int) Optional.ofNullable(redisTemplate.opsForValue().get(String.format(CHECK_PHONE_KEY, phone))).orElse(0);

        if (count >= 5) {
            return true;
        }

        count++;
        String format = String.format(CHECK_PHONE_KEY, phone);

        redisTemplate.opsForValue().set(format, count, 1, TimeUnit.DAYS);

        return false;
    }

    @Override
    public String saveCaptcha(String phone) {
        // 1.判断当前手机号是否已经获取验证码
        if (Objects.nonNull(redisTemplate.opsForValue().get(String.format(CAPTCHA_PHONE_KEY, phone)))) {
            return "";
        }

        // 2.随机生成验证码
        String random = RandomUtil.getSixBitRandom();

        redisTemplate.opsForValue().set(String.format(CAPTCHA_PHONE_KEY, phone), random, 60, TimeUnit.SECONDS);

        return random;
    }

    @Override
    public boolean checkCaptcha(String userCaptcha, String phone) {
        String captcha = (String) Optional.ofNullable(redisTemplate.opsForValue().get(String.format(CAPTCHA_PHONE_KEY, phone))).orElse("");
        return captcha.equals(userCaptcha);
    }

}
